package com.elock.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.elock.base.core.ExcelView;
import com.elock.base.core.Filter;
import com.elock.base.core.Pageable;
import com.elock.base.core.controller.BaseController;
import com.elock.base.core.controller.ResultMsg;
import com.elock.base.core.util.ConvertUtil;
import com.elock.base.core.util.DateUtil;
import com.elock.base.core.util.JsonUtils;
import com.elock.base.core.util.WebUtils;
import com.elock.service.CarSaleOrgService;
import com.elock.service.CarService;
import com.elock.service.ElockCarService;
import com.elock.service.ElockRealtimeStatusService;
import com.elock.service.TerminalMessageEventService;
import com.elock.service.TerminalMessageSendService;
import com.elock.service.TerminalPositionService;
import com.elock.service.TerminalRealtimePositionService;
import com.elock.util.SystemConfig;

/**
 * Controller - 实时监控列表
 * 
 * @author 仁德
 */
@Controller("realtimeMonitorController")
@RequestMapping("/realtime_monitor")
public class RealtimeMonitorController extends BaseController {

	@Resource(name = "carServiceImpl")
	private CarService carService;
	@Resource(name = "elockCarServiceImpl")
	private ElockCarService elockCarService;
	@Resource(name = "carSaleOrgServiceImpl")
	private CarSaleOrgService carSaleOrgService;
	@Resource(name = "terminalMessageEventServiceImpl")
	private TerminalMessageEventService terminalMessageEventService;
	@Resource(name = "elockRealtimeStatusServiceImpl")
	private ElockRealtimeStatusService elockRealtimeStatusService;
	@Resource(name = "terminalRealtimePositionServiceImpl")
	private TerminalRealtimePositionService terminalRealtimePositionService;
	@Resource(name = "terminalPositionServiceImpl")
	private TerminalPositionService terminalPositionService;
	@Resource(name = "terminalMessageSendServiceImpl")
	private TerminalMessageSendService terminalMessageSendService;

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list_tb", method = RequestMethod.GET)
	public String list_tb(ModelMap model) {

		return "/realtime_monitor/list_tb";
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Integer tabStat, Pageable pageable, ModelMap model) {

		model.addAttribute("tabStat", tabStat);
		Long lastId = terminalMessageEventService.getDaoCenter().getNativeDao()
				.findLong("select max(id) from terminal_message_event", null);
		model.addAttribute("lastId", lastId);
		return "/realtime_monitor/list";
	}

	@RequestMapping(value = "/getElockData", method = RequestMethod.POST)
	public @ResponseBody ResultMsg getElockData(String typeIds, Date elockDate) {

		List<Map<String, Object>> elockList = new ArrayList<Map<String, Object>>();
		if (!ConvertUtil.isEmpty(typeIds)) {
			String ids = "";
			String carIds = "";
			String[] typeidss = typeIds.split(";");
			for (String typeid : typeidss) {
				String[] typeidArr = typeid.split("_");
				if (Integer.parseInt(typeidArr[0]) == 2) {
					ids += "," + typeidArr[1];
				}
				if (Integer.parseInt(typeidArr[0]) == 1) {
					carIds += "," + typeidArr[1];
				}
			}
			if (!ConvertUtil.isEmpty(ids)) {
				ids = ids.substring(1);
				if (!ConvertUtil.isEmpty(carIds)) {
					carIds = carIds.substring(1);
				}
				elockList = elockRealtimeStatusService.findList(ids, carIds, elockDate);
			}
		}
		String json = JsonUtils.toJson(elockList);

		return success(json);
	}

	@RequestMapping(value = "/getTerminalData", method = RequestMethod.POST)
	public @ResponseBody ResultMsg getTerminalData(String typeIds, Date terminalDate) {

		String searchDate = null;
		List<Map<String, Object>> terminalList = new ArrayList<Map<String, Object>>();
		if (!ConvertUtil.isEmpty(typeIds)) {
			String ids = "";
			String[] typeidss = typeIds.split(";");
			for (String typeid : typeidss) {
				String[] typeidArr = typeid.split("_");
				if (Integer.parseInt(typeidArr[0]) == 3) {
					ids += "," + typeidArr[1];
				}
			}
			if (!ConvertUtil.isEmpty(ids)) {
				ids = ids.substring(1);
				terminalList = terminalRealtimePositionService.findList(ids, terminalDate);
			}
		}
		if (!terminalList.isEmpty()) {
			searchDate = DateUtil.convert((Date) terminalList.get(0).get("modify_date"));
			for (Map<String, Object> map : terminalList) {
				String onOffDate = DateUtil.convert((Date) map.get("on_off_date"));
				if (onOffDate.compareTo(searchDate) == 1) {
					searchDate = onOffDate;
				}
			}
		}
		String json = JsonUtils.toJson(terminalList);

		return success(json).addObjX(searchDate);
	}

	@RequestMapping(value = "/getMessageEventData", method = RequestMethod.POST)
	public @ResponseBody ResultMsg getMessageEventData(String typeIds, Long lastId, Integer maxcount) {

		List<Map<String, Object>> messageEventList = new ArrayList<Map<String, Object>>();
		if (!ConvertUtil.isEmpty(typeIds)) {
			String elockids = "";
			String terminalids = "";
			String[] typeidss = typeIds.split(";");
			for (String typeid : typeidss) {
				String[] typeidArr = typeid.split("_");
				if (Integer.parseInt(typeidArr[0]) == 2) {
					elockids += "," + typeidArr[1];
				}
				if (Integer.parseInt(typeidArr[0]) == 3) {
					terminalids += "," + typeidArr[1];
				}
			}
			if (!ConvertUtil.isEmpty(elockids) || !ConvertUtil.isEmpty(terminalids)) {
				if (!ConvertUtil.isEmpty(elockids)) {
					elockids = elockids.substring(1);
				}
				if (!ConvertUtil.isEmpty(terminalids)) {
					terminalids = terminalids.substring(1);
				}
				messageEventList = terminalMessageEventService.findList(elockids, terminalids, lastId, maxcount);
			}
		}
		String json = JsonUtils.toJson(messageEventList);

		return success(json);
	}

	@RequestMapping(value = "/getStatus", method = RequestMethod.POST)
	public @ResponseBody ResultMsg getStatus(String typeIds) {

		String[] typeidss = typeIds.split(";");
		String carIds = "";
		String elockIds = "";
		String terminalIds = "";
		for (String typeid : typeidss) {
			String[] typeidArr = typeid.split("_");
			if (Integer.parseInt(typeidArr[0]) == 1) {
				carIds += "," + typeidArr[1];
			} else if (Integer.parseInt(typeidArr[0]) == 2) {
				elockIds += "," + typeidArr[1];
			} else if (Integer.parseInt(typeidArr[0]) == 3) {
				terminalIds += "," + typeidArr[1];
			}
		}
		List<Map<String, Object>> list = terminalMessageEventService.getStatus(carIds, elockIds, terminalIds);

		return success().addObjX(list);
	}

	/**
	 * 列表数据
	 */
	@RequestMapping(value = "/getRealtimePosition", method = RequestMethod.POST)
	public @ResponseBody ResultMsg getRealtimePosition(Long id, Integer type, String terminalNum) {

		Map<String, Object> map = terminalMessageEventService.getRealtimePosition(id, type, terminalNum);
		return success().addObjX(map);
	}

	/**
	 * 信息下发
	 * 
	 * @param terminalId
	 * @param type
	 * @param content
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/send_msg", method = RequestMethod.POST)
	public @ResponseBody ResultMsg sendMsg(Long terminalId, Integer type, String content, HttpServletRequest request)
			throws Exception {

		Long id = terminalMessageSendService.sendMsg(terminalId, type, content, request);

		return success().addObjX(id);
	}

	/**
	 * 获取终端信息下发
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/get_message_send", method = RequestMethod.POST)
	public @ResponseBody ResultMsg getMessageSend(Long id) {

		Map<String, Object> sendMap = terminalMessageSendService.getMessageSend(id);

		return success().addObjX(sendMap);
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/track_history", method = RequestMethod.GET)
	public String trackHistory(String terminalNum, ModelMap model) {

		List<Map<String, Object>> points = new ArrayList<Map<String, Object>>();
		Date now = new Date();
		String startTime = DateUtil.convert(DateUtil.addDate("dd", -2, now));
		String endTime = DateUtil.convert(now);

		if (!ConvertUtil.isEmpty(terminalNum)) {
			points = terminalRealtimePositionService.findPointsList(terminalNum, startTime, endTime);
		}
		model.addAttribute("startTime", startTime);
		model.addAttribute("endTime", endTime);
		model.addAttribute("points", points);
		model.addAttribute("terminalNum", terminalNum);

		return "/realtime_monitor/track_history";
	}

	@RequestMapping(value = "/findHistoryPositions", method = RequestMethod.POST)
	public @ResponseBody ResultMsg findHistoryPositions(String terminalNum, String startTime, String endTime) {

		List<Map<String, Object>> points = new ArrayList<Map<String, Object>>();
		if (!ConvertUtil.isEmpty(terminalNum)) {
			points = terminalRealtimePositionService.findPointsList(terminalNum, startTime, endTime);
		}
		return success().addObjX(points);
	}

	/**
	 * 获取终端信息下发
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/get_car_info", method = RequestMethod.POST)
	public @ResponseBody ResultMsg getCarInfo(Long id) {

		String sql = "select ec.*,ers.status from elock_car ec,elock_realtime_status ers"
				+ " where ec.elock_id=ers.elock_id car_id = ?";
		List<Map<String, Object>> carInfos = carService.getDaoCenter().getNativeDao().findListMap(sql,
				new Object[] { id }, 0);

		return success().addObjX(carInfos);
	}

	@RequestMapping(value = "/to_condition_export", method = RequestMethod.POST)
	public @ResponseBody List<Map<String, Object>> toConditionExport(String terminalNum, String startTime,
			String endTime, Pageable pageable, ModelMap model) {

		Integer size = terminalPositionService.count(terminalNum, startTime, endTime);
		List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
		Map<String, Integer> segments = getSegment();
		int stage = segments.get("segment");
		int page_size = segments.get("size");
		for (int i = 0; i < stage; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			int total = i * page_size;
			if (size == 0) {
				map.put("data", "0-0");
			} else if ((size - total) <= page_size) {
				map.put("data", (total + 1) + "-" + size);
			} else {
				map.put("data", (total + 1) + "-" + (i + 1) * page_size);
			}
			lists.add(map);
			if ((size - total) <= page_size) {
				break;
			}
		}
		return lists;
	}

	/**
	 * 条件导出
	 * 
	 * @param productCategoryId
	 * @param sn
	 * @param vonderCode
	 * @param mod
	 * @param name
	 * @param startTime
	 * @param endTime
	 * @param isMarketable
	 * @param pageable
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/condition_export", method = RequestMethod.GET)
	public ModelAndView conditionExport(String terminalNum, String startTime, String endTime, Integer page,
			ModelMap model) {
		Map<String, Integer> segments = getSegment();
		int size = segments.get("size");

		List<Map<String, Object>> data = terminalPositionService.ExportProductPriceHead(terminalNum, startTime, endTime,
				page, size);
		return this.getModelAndView(data, model);
	}

	public ModelAndView getModelAndView(List<Map<String, Object>> data, ModelMap model) {

		for (Map<String, Object> map : data) {
			if (map.get("gps_time") != null) {
				String gps_time = map.get("gps_time").toString();
				map.put("gps_time", gps_time.substring(0, 19));
			}

			if (map.get("create_date") != null) {
				String create_date = map.get("create_date").toString();
				map.put("create_date", create_date.substring(0, 19));
			}
		}

		// 设置导出表格名
		String filename = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ".xls";
		// 设置标题
		String[] header = { "终端设备编号", "锁号", "电压", "基站定位数据", "经度 ", "纬度", "高程", "速度", "方向", "GPS时间 ", "状态信息描述",
				"报警信息描述 ", "备注", "版本号", "创建时间" };
		// 设置单元格取值
		String[] properties = { "terminal_num", "elock_num", "vol", "jzdw", "longitude", "latitude", "altitude",
				"speed", "direction", "gps_time", "status_desc", "warning_desc", "remark", "version", "create_date" };

		return new ModelAndView(new ExcelView(filename, null, properties, header, null, null, data, null), model);
	}

	private Map<String, Integer> getSegment() {
		HashMap<String, Integer> map = new HashMap<String, Integer>();
		try {
			String value = SystemConfig.getConfig("SegmentExportConfig", WebUtils.getCurrentCompanyInfoId());
			String[] values = value.split(",");
			map.put("segment", Integer.parseInt(values[0]));
			map.put("size", Integer.parseInt(values[1]));
		} catch (Exception e) {
			map.put("segment", 10);
			map.put("size", 1000);
		}
		return map;
	}
}
